import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout/Layout'
import error from '@/views/404'
import {getToken} from '@/utils/auth'
import {Message} from 'element-ui';
import store from "@/store";

Vue.use(VueRouter)

const routes = [
    {path: '/login', name: "登录", component: Login},
    {path: '/404', name: '404', component: error},
    {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        name: '首页',
        children: [
            {
                path: 'dashboard',
                component: () => import('@/views/dashboard/index'),
            },
        ]
    },
]

const router = new VueRouter({
    routes,
    mode: 'history'
})

/*
* 在路由生效前 统一判断有无token
* to -> 要去的路由
* from -> 当前的路由
* */

router.beforeEach((to, from, next) => {
    const token = getToken();
    if (to.path === '/login') {
        next();
    } else {
        if (token) {
            if (store.state.user.menu.length === 0 ) {
                //重新获取用户数据
                store.dispatch('getUserInfo').then(res => {
                    next({path: to.path})
                })
            }
            next()
        } else {
            Message.warning('请登录');
            next({path: '/login'});
        }
    }
})


//解决相同路径跳转报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

export default router
